#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
批量提取所有OpenBMC库的ABI信息
"""

import sys
import os
from pathlib import Path
import subprocess

# 添加当前目录到path以导入abi_extractor
sys.path.insert(0, str(Path(__file__).parent))

from abi_extractor import ABIExtractor


def main():
    """批量提取所有库的ABI"""
    # 路径配置
    project_root = Path(__file__).parent.parent.parent
    library_dir = project_root / 'data' / 'build' / 'libraries'
    output_dir = project_root / 'output' / 'abi_data'
    
    # 创建输出目录
    output_dir.mkdir(parents=True, exist_ok=True)
    
    # 获取所有.so文件（排除符号链接）
    so_files = []
    for so_file in library_dir.glob('*.so*'):
        if not so_file.is_symlink() and so_file.is_file():
            so_files.append(so_file)
    
    print(f"[INFO] 找到 {len(so_files)} 个库文件")
    print(f"[INFO] 输出目录: {output_dir}")
    print("=" * 80)
    
    # 批量提取
    success_count = 0
    failed_count = 0
    failed_libs = []
    
    for idx, so_file in enumerate(so_files, 1):
        lib_name = so_file.name
        output_file = output_dir / f"{lib_name}.abi.xlsx"
        
        print(f"\n[{idx}/{len(so_files)}] 提取 {lib_name} ...")
        
        try:
            extractor = ABIExtractor(str(so_file))
            abi_data = extractor.extract()
            extractor.save_to_excel(str(output_file), abi_data)
            success_count += 1
            print(f"  ✓ 符号数: {abi_data.statistics['total_symbols']}, "
                  f"函数: {abi_data.statistics['functions']}")
        except Exception as e:
            failed_count += 1
            failed_libs.append(lib_name)
            print(f"  ✗ 失败: {e}")
    
    # 输出摘要
    print("\n" + "=" * 80)
    print("批量提取完成！")
    print(f"总计: {len(so_files)} 个库")
    print(f"成功: {success_count} 个")
    print(f"失败: {failed_count} 个")
    
    if failed_libs:
        print(f"失败的库: {', '.join(failed_libs)}")
    
    print(f"\n输出目录: {output_dir}")
    print(f"生成文件: {success_count} 个 .xlsx + {success_count} 个 .json")
    print("=" * 80)
    
    return 0 if failed_count == 0 else 1


if __name__ == '__main__':
    sys.exit(main())

